package com.itcast.tanhuasso.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.itcast.tanhuasso.config.AliyunSMSConfig;
import com.itcast.tanhuasso.service.SmsService;
import com.itcast.tanhuasso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * @PachageName: com.itcast.tanhuasso.service.impl
 * @ClassName:
 * @Description: TODO
 * @Author: Hushi
 * @DateTime: 2021/2/721:12
 * @Version 1.0
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 阿里云发送短信接口
     * @param mobile 手机号
     * @return
     */
    @Override
    public String sendMsm(String mobile) {
        DefaultProfile profile = DefaultProfile.getProfile(this.aliyunSMSConfig.getRegionId(),
                this.aliyunSMSConfig.getAccessKeyId(), this.aliyunSMSConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        //生成验证码
        String code = RandomUtils.nextInt(100000, 999999) + "";

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(this.aliyunSMSConfig.getDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", this.aliyunSMSConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", mobile); //目标手机号
        request.putQueryParameter("SignName", this.aliyunSMSConfig.getSignName()); //签名名称
        request.putQueryParameter("TemplateCode", this.aliyunSMSConfig.getTemplateCode()); //短信模板code
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");//模板中变量替换
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            if (StringUtils.contains(data,"\"Message\":\"OK\"")){
                log.info("发送短信验证码成功 ~ , data : " + data);
                return code;
            }
            //{"Message":"OK","RequestId":"EC2D4C9A-0EAC-4213-BE45-CE6176E1DF23","BizId":"110903802851113360^0","Code":"OK"}
            System.out.println(response.getData());
        } catch (ClientException e) {
            log.info("发送短信验证码失败 ~ , mobile : " + mobile,e);
        }
        return null;
    }

    /**
     * 发送短信验证码
     * @param phone 前端获取的手机号
     * @return 固定返回结果
     */
    @Override
    public ErrorResult checkCode(String phone) {
        String yzmKey = "CHECK_CODE_" + phone;
        //判断redis中是否有已经保存的验证码,防止重复发送
        if (this.redisTemplate.hasKey(yzmKey)){
            return ErrorResult.builder().errCode("000001").errMessage("上一次发送的验证码还未失效！").build();
        }

        //阿里云发送并判断验证码是否返回(结果是否OK)
        //String code = this.sendMsm(phone);
        String code = "987654";
        if (StringUtils.isEmpty(code)){
            return ErrorResult.builder().errCode("000000").errMessage("发送短信验证码失败！").build();
        }

        //验证码发送成功,保存到redis中,60s
        redisTemplate.opsForValue().set(yzmKey,code, Duration.ofSeconds(60));
        return null;
    }
}
